<!-- 经典贪吃蛇游戏 -->
<canvas id="snakeGame" width="400" height="400"></canvas>

<script>
  const canvas = document.getElementById('snakeGame');
  const ctx = canvas.getContext('2d');
  const gridSize = 20;
  let snake = [{x: 10, y: 10}];
  let food = {x: 15, y: 15};
  let dx = 1, dy = 0;

  document.addEventListener('keydown', (e) => {
    if (e.key === 'ArrowUp' && dy !== 1) [dx, dy] = [0, -1];
    if (e.key === 'ArrowDown' && dy !== -1) [dx, dy] = [0, 1];
    if (e.key === 'ArrowLeft' && dx !== 1) [dx, dy] = [-1, 0];
    if (e.key === 'ArrowRight' && dx !== -1) [dx, dy] = [1, 0];
  });

  function gameLoop() {
    // 移动蛇头
    const head = {x: snake.x + dx, y: snake.y + dy};
    
    // 碰撞检测
    if (head.x < 0 || head.x >= 20 || head.y < 0 || head.y >= 20) 
      return alert('Game Over!');
    
    // 吃食物
    if (head.x === food.x && head.y === food.y) {
      food = {x: Math.floor(Math.random()*20), y: Math.floor(Math.random()*20)};
    } else {
      snake.pop();
    }
    
    snake.unshift(head);
    
    // 绘制
    ctx.fillStyle = '#333';
    ctx.fillRect(0, 0, 400, 400);
    ctx.fillStyle = '#4CAF50';
    snake.forEach(segment => 
      ctx.fillRect(segment.x*gridSize, segment.y*gridSize, gridSize-2, gridSize-2)
    );
    ctx.fillStyle = '#FF5722';
    ctx.fillRect(food.x*gridSize, food.y*gridSize, gridSize-2, gridSize-2);
  }
  setInterval(gameLoop, 100);
</script>
